<script setup lang="ts">
import {computed, h, reactive, ref} from 'vue'
import SearchParamCard from '@/components/SearchParamCard'
import {ActionColumns, DataTable} from '@/components/DataTable'
import {PlusRound} from "@vicons/material";
import {useMessage} from "naive-ui";
import {checkPermissionForItems, hasAnyPermission} from "@/utils";
import {deleteRequest} from "@/api";
import AddEdit from './components/add_edit.vue'
import {ModalType} from "@/utils/enums.ts";

const message = useMessage()


interface RolePermission {
  id: number;
  label?: string;
  parent_id: number;
  types: number;
  sort: number;
  children?: RolePermission[];
}

const searchParams = ref<{ key: string | null }>({
  key: '',
})

// 新增、编辑单数据
const addEditFormVisible = ref(false);
const currentEditData = ref<Recordable>({});

//数据表
const role_list = ref<InstanceType<typeof DataTable> | null>(null);
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 70,
    align: 'center',
    resizable: false
  },
  {
    title: '角色名称',
    key: 'name',
    width: 160,
  }, {
    title: '描述',
    key: 'desc',
    width: 200,
  }, {
    title: '权限',
    key: 'permission_list',
    render(row: { permission_list: RolePermission[] }) {
      const permission = row.permission_list
          .filter((item: RolePermission) => item.types === 1 && Array.isArray(item.children))
          .flatMap((item: RolePermission) => item.children || []); // 确保总是返回数组
      return permission.length ? getPermissionText(permission) : ''
    }
  }, {
    title: '创建时间',
    key: 'created_at',
    width: 175,
  }
]
//操作列及权限
const actionPermission = ['role:update', 'role:delete']//权限
const displayedActions = computed(() => {
  return checkPermissionForItems(
      actionPermission.map(p => ({perm: p})),
      obj => obj.perm
  )
})

const actionColumnWidth = computed(() => {
  const trueCount = displayedActions.value.filter(item => item).length;
  if (trueCount == 1) {
    return 50
  } else {
    return 90
  }
})

const showActionColumn = computed(() => hasAnyPermission(actionPermission))
const operationColumns = reactive({
  width: actionColumnWidth.value,
  isShow: showActionColumn.value,
  render(row: Recordable) {
    return h(ActionColumns, {
      actions: [
        {
          label: '编辑',
          type: 'primary',
          permission: actionPermission[0],
          onClick: () => {
            currentEditData.value = {
              id: row.id,
              name: row.name,
              desc: row.desc,
              permissions: row.permissions
            };
            addEditFormVisible.value = true;
          }
        },
        {
          label: '删除',
          type: 'error',
          permission: actionPermission[1],
          popConfirm: {
            content: `确定删除当前角色吗？`,
            onPositiveClick: () => {
              deleteRequest('/role/delete', row.id).then((res) => {
                if (res.code == 200) {
                  message.success(res.message, {
                    duration: 1500,
                    onLeave() {
                      role_list.value?.reload()
                    }
                  })
                } else {
                  message.error(res.message || '删除失败！')
                }
              })
            },
          }
        },
      ],
    })
  }
})
//查询数据
const searchData = () => {
  role_list.value?.searchData()
}
//关闭模态框
const handleModalClose = (modalType: ModalType) => {
  if (!role_list.value) return
  if (modalType === ModalType.SEARCH) {
    role_list.value.searchData?.()
  } else {
    role_list.value.reload?.()
  }
}

const getPermissionText = (items: RolePermission[], level: number = 0): string => {
  const sep = level === 0 ? ';' : ',';
  return items.map(item => {
    let text = item.label;
    if (item.children && item.children.length) {
      text += ':[' + getPermissionText(item.children, level + 1) + ']';
    }
    return text;
  }).join(sep);
}
</script>

<template>
  <div>
    <search-param-card @onSearch="searchData" @onReset="()=>(searchParams.key='')">
      <template #default>
        <n-form-item>
          <n-input v-model:value="searchParams.key" placeholder="请输入角色名称..." clearable/>
        </n-form-item>
      </template>
    </search-param-card>
    <n-card>
      <data-table ref="role_list"
                  :columns="columns"
                  :action-column="operationColumns"
                  :params="searchParams"
                  url="/role/lists">
        <template #toolBarLeft>
          <n-button type="primary" ghost v-permission="['role:save']"
                    @click="()=>(addEditFormVisible = true)">
            <template #icon>
              <n-icon>
                <PlusRound/>
              </n-icon>
            </template>
            新增
          </n-button>
        </template>
      </data-table>
    </n-card>
    <!--  新增、编辑  -->
    <component :is="AddEdit"
               v-model:visible="addEditFormVisible"
               :form-data="currentEditData"
               @close-modal="handleModalClose"/>
  </div>
</template>

<style scoped lang="scss">

</style>
